package org.wjw.dao;

import org.wjw.model.User;
import org.wjw.utils.DBUtil;
import org.wjw.utils.StringUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    /**
     * 接用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户信息
     */
    public User selectByUsername(String username) {
        //非空校验
        if (StringUtil.isEmpty(username)){
            return null;
        }
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet =null;


        try {
            // 1. 获取数据库连接
             connection = DBUtil.getConnection();
            // 2. 构造SQL语句
            String sql = "select id, username, password from user where username = ?";
            // 3. 获取预处理对象
             statement = connection.prepareStatement(sql);
            //替换占位符
            statement.setString(1,username);
            // 4. 提交执行SQL并获取结果
             resultSet = statement.executeQuery();
            // 5. 处理结果
            if (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 6. 关闭数据库连接，释放资源
            DBUtil.close(resultSet,statement,connection);
        }
        //如果没有查询到结果返回null
        return null;

    }

    /**
     * 按用户Id查询用户信息
     *
     * @param id 用户Id
     * @return 用户信息
     */
    public User selectById(Long id){

        // 全法性校验
        if (id == null || id <= 0) {
            return null;
        }

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet =null;


        try {
            // 1. 获取数据库连接
            connection = DBUtil.getConnection();
            // 2. 构造SQL语句
            String sql = "select id, username, password from user where id = ?";
            // 3. 获取预处理对象
            statement = connection.prepareStatement(sql);
            //替换占位符
            statement.setLong(1,id);
            // 4. 提交执行SQL并获取结果
            resultSet = statement.executeQuery();
            // 5. 处理结果
            if (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getLong("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            // 6. 关闭数据库连接，释放资源
            DBUtil.close(resultSet,statement,connection);
        }
        //如果没有查询到结果返回null
        return null;
    }

}
